﻿using System.Threading.Tasks;
using eLoop;

namespace Beeflys
{
    public abstract partial class AActor : AObject
    {
        private static DefaultQueueSchedulerAllotter schedulerAllotter = new DefaultQueueSchedulerAllotter();

        internal void Constructor(ActorId id)
        {
            base.Constructor(new ActorLogger(this));
            
            this.id = id;
            this.mailbox = new Mailbox();
            this.actorSystem = new ActorFactory(this.id);
            this.scheduler = schedulerAllotter.Next();
            
            this.scheduler.Schedule(this, null);
        }

        internal override void Destructor()
        {
            base.Destructor();
        }

        private ActorId id;
        private Mailbox mailbox;
        private ActorFactory actorSystem;
        private ITaskScheduler scheduler;
        
        public ActorId Id
        {
            get { return this.id; }
        }

        public ITaskScheduler Scheduler
        {
            get { return this.scheduler; }
        }

        private async Task InternalDestroyAsync()
        {
            if (!this.IsActive)
            {
                return;
            }

            this.IsActive = false;

            await this.ComponentsInternalDestroyAsync();
            await this.MessengerInternalDestroyAsync();
            this.actorSystem.Dispose();
            this.mailbox.Dispose();
        }
    }
}